package com.geeguo.ebuilder.operation.business.system.authorization.service.impl;

import com.geeguo.ebuilder.core.redis.service.RedisCacheService;
import com.geeguo.ebuilder.core.security.config.LoginConfig;
import com.geeguo.ebuilder.core.security.exception.PasswordException;
import com.geeguo.ebuilder.operation.base.redis.utils.CacheKeyFactory;
import com.geeguo.ebuilder.operation.business.system.authorization.service.AuthorizationService;
import com.geeguo.ebuilder.operation.business.system.user.model.UserEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AuthorizationServiceImpl implements AuthorizationService {
	
	@Autowired
    private LoginConfig loginConfig;
	@Autowired
    private RedisCacheService redisCacheService;

	@Override
	public boolean checkPassword(UserEntity user, String password) {
		int retryCount = 0;
		String retryCountKey = CacheKeyFactory.INSTANCE.getPasswordRetryCount(user.getId());
		String retryCountStr = redisCacheService.get(retryCountKey);
		if (StringUtils.isNotEmpty(retryCountStr)) {
            retryCount = Integer.valueOf(retryCountStr);
        }
        if (retryCount >= loginConfig.getPasswordRetryCount()) {
            throw new PasswordException(String.format("密码输入错误%s次，帐户锁定%s分钟", loginConfig.getPasswordRetryCount(), loginConfig.getPasswordLockTime()));
        }
        if (!password.equals(user.getPassword())) {
            retryCount = retryCount + 1;
            redisCacheService.set(retryCountKey, String.valueOf(retryCount), loginConfig.getPasswordLockTime() * 60);
            throw new PasswordException("密码输入错误");
        } else if(redisCacheService.hasKey(retryCountKey)) {
        	redisCacheService.del(retryCountKey);
        }
        return true;
    }
}
